package com.example.loginpage

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.example.loginpage.CloudSQL.MySQLConnection
import com.example.loginpage.databinding.FragmentAccountBinding
import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

class AccountFragment : Fragment() {
    private lateinit var binding: FragmentAccountBinding
    private lateinit var launcher: ActivityResultLauncher<Intent>
    private lateinit var mySQL: MySQLConnection
    private lateinit var sharedPreferences: SharedPreferences
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentAccountBinding.inflate(layoutInflater,container, false)
        launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){}
        mySQL = ViewModelProvider(this)[MySQLConnection::class.java]
        binding.VerifyView.setOnClickListener {
            val navCtl = findNavController()
            navCtl.navigate(R.id.action_AccountFragment_to_VerifyFragment)
        }

        // 读取SharedPreferences中的Boolean值
        sharedPreferences = requireActivity().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        val username = sharedPreferences.getString(KEY_USERNAME, "")
        val password = sharedPreferences.getString(KEY_PASSWORD, "")
        val rememberMe = sharedPreferences.getBoolean(KEY_REMEMBER_ME, false)

        // 为CheckBox设置OnCheckedChangeListener
        binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
            remember(isChecked)
        }
        binding.AccountText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                // 在文本变化前执行的代码
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                // 在文本变化时执行的代码
            }
            override fun afterTextChanged(s: Editable?) {
                // 在文本变化后执行的代码
                remember(binding.checkBox.isChecked)
            }
        })
        binding.PasswordText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                // 在文本变化前执行的代码
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                // 在文本变化时执行的代码
            }
            override fun afterTextChanged(s: Editable?) {
                // 在文本变化后执行的代码
                remember(binding.checkBox.isChecked)
            }
        })
        binding.AccountText.setText(username)
        binding.PasswordText.setText(password)
        binding.checkBox.isChecked = rememberMe

        response()
        return binding.root
    }
    companion object {
        const val PREFS_NAME = "login_preferences"
        private const val KEY_USERNAME = "username"
        private const val KEY_PASSWORD = "password"
        private const val KEY_REMEMBER_ME = "remember_me"

        const val STORE_NUM = "num_of_store"
        const val STORE_STRING = "string_of_store"
    }

    private fun remember(isCheck: Boolean){
        val currentUsername = binding.AccountText.text.toString()
        val currentPassword = binding.PasswordText.text.toString()

        sharedPreferences.edit()
            .putBoolean(KEY_REMEMBER_ME, isCheck)
            .apply()

        if (isCheck) {
            sharedPreferences.edit()
                .putString(KEY_USERNAME, currentUsername)
                .putString(KEY_PASSWORD, currentPassword) // 考虑在这里加密密码
                .apply()
        } else {
            sharedPreferences.edit()
                .remove(KEY_USERNAME)
                .remove(KEY_PASSWORD)
                .apply()
        }
    }
    private fun response(){
        binding.btnRegister.setOnClickListener { view ->
            onClick(view)
        }
        binding.btnLogin.setOnClickListener { view ->
            onClick(view)
        }
        mySQL.loginResponse.observe(viewLifecycleOwner) {
            if (it != null) {
                if(it.next()){
                    if(it.getString("password").equals("null")){
                        Toast.makeText(requireContext(), "该账户未设置密码，请使用短信验证登录", Toast.LENGTH_LONG).show()
                    } else{
                        if(binding.PasswordText.text.toString() == it.getString("password")){
                            Toast.makeText(requireContext(), "登陆成功", Toast.LENGTH_SHORT).show()
                            val intent = Intent(requireContext(), MainActivity::class.java)
                            intent.putExtra(Activity_Account,binding.AccountText.text.toString())
                            launcher.launch(intent)
                            activity?.finish()
                        }
                        else{
                            Toast.makeText(requireContext(), "密码错误", Toast.LENGTH_LONG).show()
                            binding.PasswordText.text.clear()
                        }
                    }
                }
                else{
                    Toast.makeText(requireContext(), "账号不存在，请先注册", Toast.LENGTH_LONG).show()
                }
            }
        }

        mySQL.registerResponse.observe(viewLifecycleOwner){
            if (it != null) {
                if (it.next()) {
                    Toast.makeText(requireContext(), "账号已存在，请登录", Toast.LENGTH_LONG).show()
                } else{
                    mySQL.updateSQL("INSERT INTO accounts (account, password) VALUES ('${binding.AccountText.text}', '${binding.PasswordText.text}');")
                    Toast.makeText(requireContext(), "注册成功", Toast.LENGTH_LONG).show()
                }
            } else{
                mySQL.updateSQL("INSERT INTO accounts (account, password) VALUES ('${binding.AccountText.text}', '${binding.PasswordText.text}');")
                Toast.makeText(requireContext(), "注册成功", Toast.LENGTH_LONG).show()
            }
        }
    }

    private fun onClick(view: View) {
        val account = binding.AccountText.text.toString().trim { it <= ' ' }
        val password = binding.PasswordText.text.toString().trim { it <= ' ' }
        val id = view.id
        when (id) {
            R.id.btnLogin -> {
                // 倘若数据库连接出现错误，可以凭借此账号密码直接登录
                if (account == "123456" && password =="123456"){
                    Toast.makeText(requireContext(), "登陆成功", Toast.LENGTH_SHORT).show()
                    val intent = Intent(requireContext(), MainActivity::class.java)
                    intent.putExtra(Activity_Account,account)
                    launcher.launch(intent)
                    activity?.finish()
                } else{
                    if (TextUtils.isEmpty(account)){
                        Toast.makeText(requireContext(), "请输入账号", Toast.LENGTH_LONG).show()
                    } else if (TextUtils.isEmpty(password)){
                        Toast.makeText(requireContext(), "请输入密码", Toast.LENGTH_LONG).show()
                    } else if(account.length<6){
                        Toast.makeText(requireContext(), "账号长度过短，请不少于6位", Toast.LENGTH_LONG).show()
                    } else if(password.length<6){
                        Toast.makeText(requireContext(), "密码长度过短，请不少于6位", Toast.LENGTH_LONG).show()
                    } else{
                        mySQL.readSQL("Select account,password From accounts Where account='$account';",1)
                    }
                }
            }

            R.id.btnRegister -> {
                if (TextUtils.isEmpty(account)){
                    Toast.makeText(requireContext(), "请输入账号", Toast.LENGTH_LONG).show()
                } else if (TextUtils.isEmpty(password)){
                    Toast.makeText(requireContext(), "请输入密码", Toast.LENGTH_LONG).show()
                } else if(account.length<6){
                    Toast.makeText(requireContext(), "账号长度过短，请不少于6位", Toast.LENGTH_LONG).show()
                } else if(password.length<6){
                    Toast.makeText(requireContext(), "密码长度过短，请不少于6位", Toast.LENGTH_LONG).show()
                }else{
                    mySQL.readSQL("Select account,password From accounts Where account='$account';",2)
                }
            }
        }
    }
}

// 密钥和初始化向量（IV）
private const val SECRET_KEY = "mySecretKey12345" // 16, 24, 或者 32 字节长
private const val INIT_VECTOR = "myInitVector1234" // 16 字节长
fun encrypt(data: String): String {
    val key = SecretKeySpec(SECRET_KEY.toByteArray(charset("UTF-8")), "AES")
    val iv = IvParameterSpec(INIT_VECTOR.toByteArray(charset("UTF-8")))

    val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
    cipher.init(Cipher.ENCRYPT_MODE, key, iv)

    val encryptedValue = cipher.doFinal(data.toByteArray(charset("UTF-8")))
    return Base64.getEncoder().encodeToString(encryptedValue)
}

fun decrypt(encryptedData: String): String {
    val key = SecretKeySpec(SECRET_KEY.toByteArray(charset("UTF-8")), "AES")
    val iv = IvParameterSpec(INIT_VECTOR.toByteArray(charset("UTF-8")))

    val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
    cipher.init(Cipher.DECRYPT_MODE, key, iv)

    val decodedByte = Base64.getDecoder().decode(encryptedData)
    val decryptedValue = cipher.doFinal(decodedByte)
    return String(decryptedValue, charset("UTF-8"))
}